import '../scss/playerList.scss'
import React from 'react'
import {userApi} from '../api/user'

export default React.createClass({
    contextTypes: {
        router: React.PropTypes.object
    },
    getInitialState() {
        return {playerList: null}
    },
    componentDidMount() {
        this.getPlayerList()
    },
    getPlayerList: function() {
        var self = this
        userApi.getPlayerList(function(err, data) {
            self.setState({playerList: data})
        })
    },
    playerLogin: function(id) {
        var self = this;
        userApi.playerLogin({
            pId: id
        }, function(err, data) {
            window.G.player = data
            var mapId = data.basicInfo.mapId
            self.context.router.push('/main')
        });
    },
    createPlayer: function() {
        var self = this,
            data = {
                name: this.refs.name.value
            }
        userApi.createPlayer(data, function(err, data) {
            self.getPlayerList()
        })
    },
    render() {
        var self = this,
            listNode;
        if (this.state.playerList && this.state.playerList.length > 0) {
            listNode = this.state.playerList.map(function(item) {
                return <div onClick={self.playerLogin.bind(self, item.pId)} key={item.pId}>{item.basicInfo.name}</div>
            })
        }
        return <div id='playerList'>
            <div>{listNode}</div>
            <div className='flex'>
                <div className='flex-col-4'>角色名</div>
                <div><input type='text' ref='name'/></div>
                <button onClick={this.createPlayer}>确定</button>
            </div>
        </div>
    }
})
